var app = require('../app');
var debug = require('debug')(app.NAME);
var Request = require('./requestHelper');

var m = {
  serverError: function(resp) {
    debug('serverError');
    resp.status(500).end();
  },
  clientError: function(resp, reason) {
    debug('clientError', reason);
    resp.status(400).send(reason).end();
  },
  serverErrorPromise: function(promise, resp) {
    return promise.fail(function(error) {
      debug('serverError', error);
      resp.status(500).send((typeof error === 'string') ? error : error.message).end();
    });
  },
  clientErrorPromise: function(promise, resp) {
    return promise.fail(function(error) {
      debug('clientError', error);
      resp.status(400).send((typeof error === 'string') ? error : error.message).end();
    })
  }
};

m.requirePermission = function (req, resp, permission) {
  var hReq = Request.instance(req);
  var permissions = hReq.userPermissions();
  if (-1 == permissions.indexOf(permission)) {
    return m.clientError(resp, '权限不足');
  }
  return req.next();
};

module.exports = m;